/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Map;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Arrays;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Eric-Standard
 */
public class MapLoader {

    public static Map loadMap(File file) {
        if (!file.canRead()) {
            return null;
        }
        Map map = new Map();
        try {
            BufferedReader fileReader = new BufferedReader(new FileReader(file));
            String propsLine = fileReader.readLine();
            int height = Integer.parseInt(propsLine);
            map.setHeight(height);
            String line = fileReader.readLine();
            int lineNum = 0;
            while (line != null) {
                if (line.length() != 3 * Map.MAP_WIDTH) {
                    break;
                }
                line = line.substring(0, line.length() - 1);
                String[] split = line.split("[ ]+");
                System.out.println(Arrays.toString(split));
                if (split.length != Map.MAP_WIDTH) {
                    break;
                }
                for (int i = 0; i < split.length; i++) {
                    int a = Integer.parseInt(split[i], 16);
                    if (a > Map.DEFAULT_TILES.length) {
                        break;
                    }
                    map.arr[lineNum][i] = Map.DEFAULT_TILES[a];
                }
                line = fileReader.readLine();
                lineNum++;
            }
            fileReader.close();
            map.generateMapObjects();
        } catch (IOException ex) {
            Logger.getLogger(MapLoader.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NumberFormatException ex) {
            Logger.getLogger(MapLoader.class.getName()).log(Level.SEVERE, null, ex);
        }
        return map;
    }
}
